//
//  MusicPlay.m
//  One
//
//  Created by mac on 16/5/30.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MusicPlay.h"
#import "MiniMusicControlViewViewController.h"

@implementation MusicPlay
{
    MiniMusicControlViewViewController *miniVC;
}

static MusicPlay *player = nil;
+ (id)shareAVPlay
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!player) {
            player = [[super allocWithZone:NULL]init];
        }
    });
    
    return player;
}

- (void)playMusicWithUrl:(NSURL *)url CurrentPlayItem:(MusicModleObject *)currentPlayItem{
    miniVC = [MiniMusicControlViewViewController shareMiniVC];
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _arrayPlayList = [[NSMutableArray alloc]init];
    });
    
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:url];
    [_arrayPlayList addObject:item];

    _avPlayer = [[AVQueuePlayer alloc]initWithPlayerItem:item];
    self.currenPlayItem = currentPlayItem;
    [NOTI_CENTER addObserver:self selector:@selector(playDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    miniVC.showObj = currentPlayItem;
//    [_avPlayer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//    __weak AVPlayer *weakPlyer = _avPlayer;
//    [_avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//        float currentTime = weakPlyer.currentItem.currentTime.value/weakPlyer.currentItem.currentTime.timescale;
//        
//    }];
    
}

- (void)playAnthorMusicWithUrl:(NSURL *)url CurrentPlayItem:(MusicModleObject *)currentPlayItem
{
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:url];
    [_arrayPlayList addObject:item];
    
    _avPlayer = [AVQueuePlayer playerWithURL:url];
    self.currenPlayItem = currentPlayItem;
    miniVC.showObj = currentPlayItem;
}

- (void)playDidEnd
{
    NSLog(@"播放完毕");
    [_avPlayer advanceToNextItem];
    
}

- (void)doPlay
{
    
    if (_isPlaying) {
        [_avPlayer pause];
        _isPlaying = NO;
    }
    else
    {
        _isPlaying = YES;
        [_avPlayer play];
        NSLog(@"play");
    }
    
    [NOTI_CENTER postNotificationName:@"play" object:nil];
}

//- (void)playMusicWithMusicPage:(int)page
//{
//    _avPlayer 
//    
//}

@end
